﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using MvcCms.Service;
using MvcCms.Service.Filters;
using MvcCms.Data;
using Microsoft.Practices.ServiceLocation;
using MvcCms.Service.Cache;
using MvcCms.Data.Entities;

namespace MvcCms.Service.Code.BaseClasses
{
    public abstract class CMSControllerBase : MvcCmsControllerBase
    {
        #region Constructors
        private ICmsService _service;
        private IZoneService _zoneService;
        private IAccountService _accountService;
        public CMSControllerBase(ICmsService cmsService, IZoneService zoneService, IAccountService accountService)
        {
            _service = cmsService;
            _accountService = accountService;
            _zoneService = zoneService;
        }
        #endregion

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (TempData["ModelState"] != null && !ModelState.Equals(TempData["ModelState"]))
                ModelState.Merge((ModelStateDictionary)TempData["ModelState"]);

            base.OnActionExecuted(filterContext);
        }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            //MvcCms Specific
            string[] roles = new string[0];
            var user = _accountService.GetUser();
            if (user != null)
            {
                roles = Roles.GetRolesForUser();
            }
            try
            {
                var zoneHTMLs = new List<DTOZoneHTML>();
                var widgets = _service.ListWidgetsForZones();
                foreach (var widget in widgets)
                {
                    var currentPage = _service.GetContentPageForRequest();
                    int themeId = 0;
                    if (currentPage != null) { themeId = currentPage.ThemeID.GetValueOrDefault(); }
                    var zones = _zoneService.ListZones(themeId);
                    if (zones != null)
                    {
                        foreach (var zone in zones)
                        {
                            if (widget.ZoneName.ToLower() == zone.Name.ToLower())
                            {
                                var newZoneHTML = new DTOZoneHTML
                                {
                                    ZoneName = zone.Name,
                                    HTML = _zoneService.GetZoneHTML(widget, Request.IsAuthenticated, roles)
                                };
                                zoneHTMLs.Add(newZoneHTML);
                            }
                        }
                    }
                }
                ViewBag.ZoneHTMLs = zoneHTMLs;
            }
            catch
            {
                //if the above failed most likely the url does not match the portal, lets see if there is a redirect for this
                //for instance the non www version, we are going to assume the http protocol here
                var url = Request.Url.Host.ToLower();
                var redirect = _service.GetGlobalRedirect("http://" + url);
                if (redirect != null)
                {
                    requestContext.HttpContext.Response.StatusCode = 301;
                    requestContext.HttpContext.Response.RedirectLocation = redirect.NewPage;
                    requestContext.HttpContext.Response.End();
                }
                else
                {
                    //let's make a redirect for the default portal
                    var portalService = ServiceLocator.Current.GetInstance<IPortalService>();
                    var defaultPortal = portalService.GetPortalByName("default");
                    var newRedirect = new Redirect
                    {
                        Portal = defaultPortal,
                        Description = "Auto Generated By MvcCms",
                        NewPage = "http://" + defaultPortal.URLAuthority + "/notfound",
                        OldPage = "http://" + url
                    };
                    _service.CreateRedirect(newRedirect);
                    requestContext.HttpContext.Response.StatusCode = 301;
                    requestContext.HttpContext.Response.RedirectLocation = newRedirect.NewPage;
                    requestContext.HttpContext.Response.End();
                }
            }
        }
    }
}